import { login, logout } from '@/api/login';
import {
getLoginStatus, setLoginStatus, removeLoginStatus,
getLoginRole, setLoginRole, removeLoginRole,
getLoginName, setLoginName
} from '@/utils/auth';

const user = {
  state: {
    loginStatus: !+getLoginStatus(),
    name: getLoginName(),
    roles: [getLoginRole()]
  },

  mutations: {
    SET_LOGIN_STATUS: (state, loginStatus) => {
      state.loginStatus = loginStatus;
      setLoginStatus(loginStatus);
      if (!loginStatus) {
          removeLoginStatus();
      }
    },
    SET_NAME: (state, name) => {
      state.name = name;
      setLoginName(name);
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
      if (roles && roles.length > 0) {
          setLoginRole(roles[0]);
      } else {
          removeLoginRole();
      }
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password.trim();
      return new Promise((resolve, reject) => {
        login(username, password).then(response => {
          if (response.code === 0) {
              commit('SET_NAME', username);
              commit('SET_ROLES', [response.data]);
              commit('SET_LOGIN_STATUS', 1);
          } else {
              commit('SET_NAME', '');
              commit('SET_ROLES', []);
              commit('SET_LOGIN_STATUS', 0);
          }
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('SET_NAME', '');
          commit('SET_ROLES', []);
          commit('SET_LOGIN_STATUS', 0);
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_NAME', '');
        commit('SET_ROLES', []);
        commit('SET_LOGIN_STATUS', 0);
        resolve();
      });
    }
  }
};

export default user;
